interface PreData<T> {
	data: T,
	expire: number
}
class Cache {
	private cacheSetHandler = uni.setStorageSync;
	private cacheGetHandler = uni.getStorageSync;
	private cacheClearHandler = uni.removeStorageSync;
	
	constructor() {
		
	}
	
	/**
	 * 获取当前时间戳
	 */
	private getNowTimestamp() {
		return new Date().getTime();
	}
	
	/**
	 * 设置缓存
	 * @param key 缓存名
	 * @param value 缓存值
	 * @param expire 过期时间
	 */
	setCache<T = any>(key: string, value: T, expire: number = -1) {
		this.cacheSetHandler(key, JSON.stringify({
			data: value,
			expire
		}))
	}
	
	/**
	 * 获取缓存
	 * @param key 缓存名
	 */
	getCache<V = any>(key: string): V | null {
		const noDealData = this.cacheGetHandler(key);
		if(!noDealData) return null;
		const preData: PreData<V> = JSON.parse(noDealData);
		if(preData.expire >= 0 && preData.expire - this.getNowTimestamp() <= 0) return null;
		return preData.data;
	}
	
	/**
	 * 清理缓存
	 * @param key 缓存名
	 */
	clearCache(key: string) {
		this.cacheClearHandler(key);
	}
}

export default new Cache();